﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Domian.Entities;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public CreateUserHandler(IBaseRepository<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            var role= roleRepo.GetAll().Where(x=>x.RoleName==request.RoleName).FirstOrDefault();
            if(role != null)
            {
                res.Message = "角色名称不能重复";
                res.Code = ApiEnum.File;
                return Task.FromResult(res);
            }
            var entity = mapper.Map<RoleModel>(request);
            var r = roleRepo.Add(entity).Result;
            if (r > 0)
            {
                res.Message = "新增成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "新增失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
